// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import {I18n, Logger} from '@aws-amplify/core';
import {useHistory, useLocation} from 'react-router';
import {useEffect, useState, Fragment} from 'react';
import {API} from '@aws-amplify/api';
import {API_NAME} from '../util/Utils';
import PageTitleBar from '../components/Shared/PageTitleBar';
import Footer from '../components/Shared/Footer';
import Card from 'react-bootstrap/Card';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import Row from 'react-bootstrap/Row';
import Alert from 'react-bootstrap/Alert';
import {IDevice, IPageProps, IErrors} from '../components/Shared/Interfaces';

interface IProps extends IPageProps {
  device?: IDevice
}

export default function DeviceModify(props: any): JSX.Element {
  const history = useHistory();
  const logger = new Logger("Device modification");
  const { location } = props
  const [device, setDevice] = useState<IDevice>({
    thingName: "",
    thingTypeName: "",
    thingArn: "",
    status: "",
    temperature: '1',
    version: 0
  });
  const [errs, setErrs] = useState<IErrors<IDevice>>({
    temperature: '大于等于15并小于等于40',
    status: '需要等于aaa'
  });
  const [showAlert, setShowAlert] = useState("");
  const [showValidation, setShowValidation] = useState<string[]>([]);
  const [statusErr, setStatusErr] = useState<boolean>(false)
  const [temperatureErr, setTemperatureErr] = useState<boolean>(false)

  /**
   * react useEffect hoook
   * runs on device state change
   * validates device form fields
   */
  // useEffect(() => {
  //   let newErrs = {};
  //   //todo validations
  //   setErrs({...newErrs});
  // }, [device])

  const loadDevice = async () => {
    const thingName = location.pathname.split('/').pop();
    try {
      const results = await API.get(API_NAME, `/devices/${thingName}`, {});
      setDevice(results);
    } catch (err: any) {
      logger.error(I18n.get("device.get.error"), err);
    }
  }

  /**
   * react useEffect hook
   * load simulation and needed device type info (topic, id) on load
   * and initializes map if auto demo
   */
  useEffect(() => {
    loadDevice();
  }, []);

  /**
   * updates state on form changes
   * @param event
   */
  const handleFormChange = (event: any) => {
    let value = event.target.valueAsNumber || event.target.value;

    switch (event.target.id) {
      case "temperature":
        device.temperature = value;
        break;
      case "status":
        device.status = value;
        break;
      default:
        return;
    }

    // device[event.target.id as keyof IDevice] = event.target.value;
    setDevice({...device})
  }

  /**
   * Shows form validation when a field is focused
   * @param event
   */
  const handleFieldFocus = (event: any) => {
    // if (!showValidation.includes(event.target.id)) {
    //   showValidation.push(event.target.id);
    //   setShowValidation([...showValidation]);
    // }
    switch (event.target.id) {
      case "temperature":
        (device.temperature && (Number(device.temperature) < 15 || Number(device.temperature) > 40)) ? setTemperatureErr(true) : setTemperatureErr(false)
        break;
      case "status":
        (device.status && device.status !== 'aaa') ? setStatusErr(true) : setStatusErr(false)
        break;
      default:
        return;
    }
  }

  /**
   * updates device state on form submission
   */
  const handleSubmit = async (event: any) => {
    const form = event.currentTarget;
    event.preventDefault();
    form.checkValidity();
    if (Object.keys(errs).length > 0) {
      return;
    }

    try {
      await API.post(API_NAME, '/devices/{}', {body: device});
      history.push('/devices');
    } catch (err) {
      logger.error(I18n.get("device.modification.error"), err);
      throw err;
    }

  }

  return (
    <div>
      <PageTitleBar title={props.title}/>
      <Card className="content-card" style={{ border: '0' }}>
        <Card.Title className="content-card-title">
          {I18n.get("device.modification")}
        </Card.Title>
        <Card.Subtitle className="content-card-subtitle">
          {I18n.get("device.modify.description")}: {device?.thingName}
        </Card.Subtitle>
        <Alert show={!!showAlert} variant="danger" onClose={() => setShowAlert("")} dismissible>
          <Alert.Heading>{I18n.get('json.error')}</Alert.Heading>
          <div>
            {showAlert.split('\n').map((line, index) => <p key={index}>{line}</p>)}
          </div>
        </Alert>
        <Card.Body>
          <Form
            name="deviceForm"
            id="deviceForm"
            onSubmit={(event) => {
              handleSubmit(event)
            }}
          >
            <Form.Group className="form-item-spacing">
              <Form.Label>{I18n.get("device.status")}</Form.Label>
              <Form.Control
                type="text"
                id="status"
                maxLength={128}
                value={device.status}
                onChange={(event) => handleFormChange(event)}
                onBlur={(event: any) => handleFieldFocus(event)}
                // isInvalid={!!errs.status && showValidation.includes('status')}
                isInvalid={statusErr}
                // isValid={!errs.status && showValidation.includes('status')}
              >
              </Form.Control>
              <Form.Control.Feedback type="invalid">{errs.status}</Form.Control.Feedback>
              <Form.Text className="muted">
                {I18n.get("device.status.description")}
              </Form.Text>
            </Form.Group>
            <Form.Group className="form-item-spacing">
              <Form.Label>{I18n.get("device.temperature")}</Form.Label>
              <Form.Control
                type="number"
                id="temperature"
                min={15}
                max={40}
                value={Number(device.temperature)}
                isInvalid={temperatureErr}
                // isInvalid={!!errs.temperature && showValidation.includes('temperature')}
                // isValid={!errs.temperature && showValidation.includes('temperature')}
                onChange={(event) => handleFormChange(event)}
                onBlur={(event: any) => handleFieldFocus(event)}
              >
              </Form.Control>
              <Form.Control.Feedback type="invalid">{errs.temperature}</Form.Control.Feedback>
              <Form.Text className="muted">
                {I18n.get("device.temperature.description")}
              </Form.Text>
            </Form.Group>
            <Form.Label>{I18n.get("payload.sample")}</Form.Label>
            <Row className="float-right">
              <Button
                className="button-theme"
                form="deviceForm"
                type="submit"
                // disabled={Object.keys(errs).length > 0}>
                disabled={temperatureErr || statusErr}>
                {I18n.get("save")}
              </Button>
              <Button
                style={{ marginLeft: '10px' }}
                className="button-theme-alt"
                onClick={() => {
                  history.goBack()
                }}>
                {I18n.get("cancel")}
              </Button>
            </Row>
          </Form>
        </Card.Body>
      </Card>
      <Footer pageTitle={props.title}/>
    </div>
  );
}